package com.whjfxx.terminal.message;

import com.sun.mail.util.MailSSLSocketFactory;
import com.whjfxx.terminal.utils.CodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.message.MessageFormatMessage;
import org.apache.logging.log4j.message.ParameterizedMessageFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.text.MessageFormat;
import java.util.Properties;

/**
 * Created by b.c on 2022/6/27 11:12
 */
@Slf4j
public class EmailServer {

    static EmailServer emailServer = null;

    Properties properties;

    private final static String MAIL_HOST = "smtp.qq.com";

    private final static String MAIL_TRANSPORT_PROTOCOL = "smtp";

    private final static String MAIL_SMTP_AUTH = "true";

    private final static String MAIL_SMTP_SSL_ENABLE = "true";

    private final static String USER_NAME = "893501636@qq.com";

    private final static String PASSWORD = "mzbzjyhifmhebbcg";

    private final static String FROM_MAIL = "893501636@qq.com";


    private final static MailSSLSocketFactory sf () throws GeneralSecurityException {
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        return sf;
    }

    private EmailServer() throws GeneralSecurityException {
        properties = new Properties();
        properties.setProperty("mail.host", MAIL_HOST);
        properties.setProperty("mail.transport.protocol", MAIL_TRANSPORT_PROTOCOL);
        properties.setProperty("mail.smtp.auth", MAIL_SMTP_AUTH);
        properties.put("mail.smtp.ssl.enable", MAIL_SMTP_SSL_ENABLE);
        properties.put("mail.smtp.ssl.socketFactory", sf());
    }

    public static EmailServer getInstance() {
        try {
            if (null == emailServer) {
                emailServer = new EmailServer();
            }
            return emailServer;
        } catch (GeneralSecurityException e) {
            log.warn("邮件服务加载失败", e);
            throw new RuntimeException("邮件服务加载失败");
        }
    }

    public void send(String receipt, String subject, String content) throws MessagingException {
        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(USER_NAME,PASSWORD);
            }
        });
        //开启debug模式
        session.setDebug(true);
        //获取连接对象
        Transport transport = session.getTransport();
        //连接服务器
        transport.connect(MAIL_HOST,USER_NAME,PASSWORD);
        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        //邮件发送人
        mimeMessage.setFrom(new InternetAddress(FROM_MAIL));
        //邮件接收人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(receipt));
        //邮件标题
        mimeMessage.setSubject(subject);
        //邮件内容
        mimeMessage.setContent(content,"text/html;charset=UTF-8");
        //发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        //关闭连接
        transport.close();
    }

    public static void main(String[] args) throws MessagingException {
        EmailServer.getInstance().send("893501636@qq.com", "xxxxx", ParameterizedMessageFactory.INSTANCE.newMessage(MESSAGE_TEMPLATE, CodeUtil.genCode(6)).getFormattedMessage());
    }


    private static String MESSAGE_TEMPLATE = "<head>\n" +
            "    <base target=\"_blank\" />\n" +
            "    <style type=\"text/css\">::-webkit-scrollbar{ display: none; }</style>\n" +
            "    <style id=\"cloudAttachStyle\" type=\"text/css\">#divNeteaseBigAttach, #divNeteaseBigAttach_bak{display:none;}</style>\n" +
            "    <style id=\"blockquoteStyle\" type=\"text/css\">blockquote{display:none;}</style>\n" +
            "    <style type=\"text/css\">\n" +
            "        body{font-size:14px;font-family:arial,verdana,sans-serif;line-height:1.666;padding:0;margin:0;overflow:auto;white-space:normal;word-wrap:break-word;min-height:100px}\n" +
            "        td, input, button, select, body{font-family:Helvetica, 'Microsoft Yahei', verdana}\n" +
            "        pre {white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;width:95%}\n" +
            "        th,td{font-family:arial,verdana,sans-serif;line-height:1.666}\n" +
            "        img{ border:0}\n" +
            "        header,footer,section,aside,article,nav,hgroup,figure,figcaption{display:block}\n" +
            "        blockquote{margin-right:0px}\n" +
            "    </style>\n" +
            "</head>\n" +
            "<body tabindex=\"0\" role=\"listitem\">\n" +
            "<table width=\"700\" border=\"0\" align=\"center\" cellspacing=\"0\" style=\"width:700px;\">\n" +
            "    <tbody>\n" +
            "    <tr>\n" +
            "        <td>\n" +
            "            <div style=\"width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;\">\n" +
            "                <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"700\" height=\"39\" style=\"font:12px Tahoma, Arial, 宋体;\">\n" +
            "                    <tbody><tr><td width=\"210\"></td></tr></tbody>\n" +
            "                </table>\n" +
            "            </div>\n" +
            "            <div style=\"width:680px;padding:0 10px;margin:0 auto;\">\n" +
            "                <div style=\"line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;\">\n" +
            "                    <strong style=\"display:block;margin-bottom:15px;\">尊敬的用户：<span style=\"color:#f60;font-size: 16px;\"></span>您好！</strong>\n" +
            "                    <strong style=\"display:block;margin-bottom:15px;\">\n" +
            "                        您正在进行<span style=\"color: red\">登录帐号</span>操做，请在验证码输入框中输入：<span style=\"color:#f60;font-size: 24px\">{}</span>，以完成操做。\n" +
            "                    </strong>\n" +
            "                </div>\n" +
            "                <div style=\"margin-bottom:30px;\">\n" +
            "                    <small style=\"display:block;margin-bottom:20px;font-size:12px;\">\n" +
            "                        <p style=\"color:#747474;\">\n" +
            "                            注意：此操做可能会修改您的密码、登陆邮箱或绑定手机。如非本人操做，请及时登陆并修改密码以保证账户安全\n" +
            "                            <br>（工作人员不会向你索取此验证码，请勿泄漏！)\n" +
            "                        </p>\n" +
            "                    </small>\n" +
            "                </div>\n" +
            "            </div>\n" +
            "            <div style=\"width:700px;margin:0 auto;\">\n" +
            "                <div style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">\n" +
            "                    <p>此为系统邮件，请勿回复<br>\n" +
            "                        请保管好您的邮箱，避免帐号被他人盗用\n" +
            "                    </p>\n" +
            "                    <p>武汉玖复信息科技 网络科技团队</p>\n" +
            "                </div>\n" +
            "            </div>\n" +
            "        </td>\n" +
            "    </tr>\n" +
            "    </tbody>\n" +
            "</table>\n" +
            "</body>";
}
